package org.wkg.lesson10;

import java.util.concurrent.*;

public class Demo_1101 {

    public static void main(String[] args) {
        //使用Callable来定义任务

        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 1; i <= 1000; i++) {
                    sum += i;
                }
                TimeUnit.SECONDS.sleep(1);
                throw new IllegalArgumentException("计算错误");
                //return sum;
            }
        };
        //Callable需要配合FutureTask来使用，FutureTask里面要Runnable类
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        //将FutureTask传入Thread线程中来执行Callable创建的任务
        Thread thread = new Thread(futureTask);

        thread.start();


        //Callable中的Call方法需要捕获异常，如果在计算时候发生错误就可以提醒我们
        try {
            Integer result = futureTask.get();//任务未完成时候会一直堵塞，知道任务完成才不堵塞
            System.out.println("执行结果是：" + result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            System.out.println("已解锁");
            e.printStackTrace();
            e.getMessage();
        }


    }

}

